<template>
	<view style="overflow: hidden;height: 100%;">
		<!-- <CustomNavbar :title="pageTitle" :rightButtons="rightBtns" @share="onShare" /> -->
		<view style="height: 100px;line-height: 135px;text-align: center;font-size: 14px;font-weight: bold;">
			报名填写
		</view>
		<view class="container">
			<view class="form-container">
				<view class="form-group">
					<view class="label">岗位名称</view>
					<picker @change="changePickerPost" :value="formData.post" :range="postList" :range-key="'name'">
						<view class="uni-input">{{postIndex ? postList[postIndex].name : '请选择岗位名称'}} </view>
					</picker>
					<!-- <input type="text" class="input" placeholder="请输入姓名" v-model="formData.name" /> -->
				</view>
				<view class="form-group">
					<view class="label">姓名</view>
					<input type="text" class="input" placeholder="请输入姓名" v-model="formData.studentName" />
				</view>

				<view class="form-group">
					<view class="label">性别</view>
					<view class="radio-group">
						<view @click="setSex(1)"
							:class="['default-box',formData.gender == 1 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							男
						</view>
						<view @click="setSex(0)"
							:class="['default-box',formData.gender == 0 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							女
						</view>
					</view>
				</view>

				<view class="form-group">
					<view class="label">出生年月</view>
					<picker mode="date" :value="formData.bornDate" start="1900-01-01" end="2025-12-31"
						@change="handleBornChange">
						<view class="picker">
							{{ formData.bornDate || '请选择出生年月' }}
						</view>
					</picker>
				</view>

				<view class="form-group">
					<view class="label">电话</view>
					<input type="tel" class="input" placeholder="请输入电话号码" v-model="formData.mobilePhone" />
				</view>



				<view class="form-group">
					<view class="label">毕业时间</view>
					<picker mode="date" :value="graduateYear" start="1900-01-01" end="2025-12-31"
						@change="handleGraduationDateChange">
						<view class="picker">
							{{ graduateYear || '请选择毕业时间' }}
						</view>
					</picker>
				</view>

				<view class="form-group">
					<view class="label">所学专业</view>
					<input type="text" class="input" placeholder="请输入专业" v-model="formData.subjectName" />
				</view>


				<view class="form-group">
					<view class="label">在职情况</view>
					<picker :range="jobedOptions" :range-key="'name'" :value="formData.jobed" @change="handJobedChange">
						<view class="picker">
							{{ jobedOptions[formData.jobed].name || '请选择在职情况' }}
						</view>
					</picker>
				</view>

				<view class="form-group">
					<view class="label">出发城市</view>
					<picker mode="region" :value="setoutArea" @change="handleCityChange">
						<view class="picker">
							{{ setoutArea && setoutArea.length > 0 ? setoutArea.join(' ') : '请选择城市' }}
						</view>
					</picker>
				</view>
				<view class="form-group">
					<view class="label">是否买票</view>
					<view class="radio-group">
						<view @click="setBuyTicketed(1)"
							:class="['default-box',formData.buyTicketed == 1 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							是
						</view>
						<view @click="setBuyTicketed(0)"
							:class="['default-box',formData.buyTicketed == 0 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							否
						</view>
					</view>
				</view>
				<view class="form-group">
					<view class="label">实训地</view>
					<input type="text" class="input" placeholder="请输入实训地" v-model="formData.schoolAddr" />
				</view>



			</view>
			<view class="form-container">
				<view class="form-group">
					<view class="label" style="width: 45%;">全日制最高学历</view>
					<picker :range="qualificationOptions" :range-key="'name'" :range-value="'value'"  :value="qualificationIndex"
						@change="handleEducationChange">
						<view class="picker">
							{{ qualificationOptions[qualificationIndex].name || '请选择学历' }}
						</view>
					</picker>
				</view>
				<view class="form-group">
					<view class="label" style="width: 45%;">之前从事职业</view>
					<input type="text" class="input" placeholder="请输入之前从事职业" v-model="formData.oldWork" />
				</view>
				<view class="form-group">
					<view class="label" style="width: 45%;">上份工作薪资</view>
					<input type="number" class="input" style="flex: 1;" placeholder="请输入薪资"
						v-model="formData.oldSalary" />
					<view style="width: 25%;">（元/月）</view>
				</view>
				<view class="form-group">
					<view class="label" style="width: 40%;">预计到达校区时间</view>
					<view style="display: flex;align-items: center;justify-content: space-between;flex: 1;">
						<picker style="width:60%" mode="date" :value="arriveDate" start="1900-01-01" end="2025-12-31"
							@change="handleDateChange">
							<view class="picker">
								{{ arriveDate || '请选择日期' }}
							</view>
						</picker>
						<picker style="width: 41%;" mode="time" :value="arriveTime" start="1900-01-01" end="2025-12-31"
							@change="handleTimeChange">
							<view class="picker">
								{{ arriveTime || '请选择时间' }}
							</view>
						</picker>
					</view>
				</view>
				<view class="form-group">
					<view class="label" style="width: 45%;">是否需要住宿</view>
					<view class="radio-group">
						<view @click="setNeedDorm(1)"
							:class="['default-box',formData.needDorm == 1 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							是
						</view>
						<view @click="setNeedDorm(0)"
							:class="['default-box',formData.needDorm == 0 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							否
						</view>

					</view>
				</view>
				<view class="form-group">
					<view class="label" style="width: 45%;">是否有以下特殊情况</view>
					<view class="radio-group">
						<view @click="setBad(1)" :class="['default-box',formData.bad == 1 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							是
						</view>
						<view @click="setBad(0)" :class="['default-box',formData.bad == 0 ? 'active-default-box' : '']"
							style="margin-right: 4px;">
							否
						</view>
					</view>
				</view>

			</view>
			<view class="button-group">
				<button class="btn reset-btn" @click="resetForm">重置</button>
				<button class="btn submit-btn" @click="submitForm">提交</button>
			</view>

		</view>
	</view>
</template>

<script>
	import CustomNavbar from '@/components/customNavbar.vue'
	import {
		signUpSave
	} from '../api/index.js'
	export default {
		components: {
			CustomNavbar
		},
		data() {
			return {
				setoutArea: [],
				postList: [{
						value: 0,
						name: '云计算'
					},
					{
						value: 1,
						name: '大数据'
					},
					{
						value: 2,
						name: '技能认证'
					},
					{
						value: 3,
						name: '无人机'
					},
				],
				jobedOptions: [{
						value: 0,
						name: '离职'
					},
					{
						value: 1,
						name: '在职'
					},
					{
						value: 2,
						name: '待业'
					},
				],
				qualificationOptions: [{
						value: 13,
						name: '大专（自考/成考/函授）'
					},
					{
						value: 14,
						name: '本科（自考/成考/函授）'
					},
					{
						value: 15,
						name: '大专（全日制）'
					},
					{
						value: 16,
						name: '本科（全日制）'
					},
					{
						value: 19,
						name: '硕士'
					},
					{
						value: 10,
						name: '其他'
					},
				],
				arriveDate: '',
				arriveTime: '',
				jobedIndex: 0,
				statusBarHeight: 0,
				navBarHeight: 44,
				safeAreaInsetsTop: 0,
				isImobilePhoneX: false,
				pageTitle: '报名信息',
				rightBtns: [{
					icon: 'icon-share',
					callback: 'share'
				}],
				qualificationIndex:null,
				postIndex:null,
				graduateYear: '',
				formData: {
					studentName:'',
					post: null,
					qualification:null,
					jobed: 0,
					gender: 1,
					bornDate: '',
					mobilePhone: '',
					graduateDate: '',
					oldWork: '',
					schoolAddr: '',
					subjectName: '',
					buyTicketed: 1,
					needDorm: 1,
					bad: 1,
				},
				educationIndex: 0,
				errors: {},
				selectedDate: ''
			}
		},
		onLaunch: function() {
			console.log(pages.pages)
			const token = uni.getStorageSync('token');
			const targetPath = '/pages/login/login';
			if (token) {
				plus.navigator.closeSplashscreen();
			} else {
				uni.reLaunch({
					url: targetPath
				});
			}
			// uni.reLaunch({ url: targetPath });
		},
		methods: {
			// 设置性别
			setSex(val) {
				this.formData.gender = val
			},
			// 设置是否买票
			setBuyTicketed(val) {
				this.formData.buyTicketed = val
			},
			// 设置是否需要住宿
			setNeedDorm(val) {
				this.formData.needDorm = val
			},
			// 设置是否需要住宿
			setBad(val) {
				this.formData.bad = val
			},
			changePickerPost(e) {
				this.postIndex = e.detail.value
				this.formData.post = this.postList[e.detail.value].value
				
			},
			leRadioChange(value) {
				this.formData.gender = value
				this.validateField('gender', value)
			},
			// 设置到校日期
			handleBornChange(e) {
				console.log(e)
				this.formData.bornDate = e.detail.value
			},
			// 设置到校日期
			handleDateChange(e) {
				console.log(e.detail.value)
				this.arriveDate = e.detail.value
			},
			// 设置到校时间
			handleTimeChange(e) {
				console.log(e)
				this.arriveTime = e.detail.value
			},
			// 设置在职情况
			handJobedChange(e) {
				this.jobedIndex = e.detail.value
				this.formData.jobed = e.detail.value
			},
			// 设置学历
			handleEducationChange(e) {
				this.qualificationIndex = e.detail.value
				this.formData.qualification = this.qualificationOptions[e.detail.value].value
				console.log('e',this.formData.qualification)
			},
			// 设置毕业时间
			handleGraduationDateChange(e) {
				this.graduateYear = e.detail.value
			},
			handleCityChange(e) {
				console.log(e)
				this.setoutArea = e.detail.value
			},
			selectRegistrationTime() {
				const now = new Date()
				this.selectedDate = this.formatDate(now)

				// 显示日期选择器
				uni.showActionSheet({
					itemList: this.generateDateOptions(now),
					success: (res) => {
						const selectedIndex = res.tapIndex
						if (selectedIndex === 0) {
							// 今天
							this.selectedDate = this.formatDate(now)
						} else if (selectedIndex === 1) {
							// 明天
							const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000)
							this.selectedDate = this.formatDate(tomorrow)
						}

						// 显示时间选择器
						this.showTimePicker()
					},
					fail: (err) => {
						console.log(err.errMsg)
					}
				})
			},

			formatDate(date) {
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
			},

			generateDateOptions(now) {
				const options = ['今天', '明天']
				return options
			},

			showTimePicker() {
				const now = new Date()
				const isToday = this.selectedDate === this.formatDate(now)
				const currentHour = now.getHours()

				// 生成时间选项
				let hours = []
				if (isToday) {
					// 今天只显示当前时间及之后的小时
					for (let i = currentHour; i < 24; i++) {
						hours.push(i.toString().padStart(2, '0'))
					}
				} else {
					// 明天显示所有小时
					for (let i = 0; i < 24; i++) {
						hours.push(i.toString().padStart(2, '0'))
					}
				}

				// 显示小时选择器
				uni.showActionSheet({
					itemList: hours.map(hour => `${hour}:00`),
					success: (res) => {
						this.selectedHour = hours[res.tapIndex]
						this.formData.registrationTime = `${this.selectedDate} ${this.selectedHour}:00`
						this.validateField('registrationTime', this.formData.registrationTime)
					},
					fail: (err) => {
						console.log(err.errMsg)
					}
				})
			},
			resetForm() {
				this.formData = {
					name: '',
					gender: '',
					birthday: '',
					mobilePhone: '',
					education: '',
					graduationDate: '',
					oldWork: '',
					oldSalary: '',
					occupation: '',
					city: [],
				}
				this.educationIndex = 0
				this.errors = {}
			},
			validateField(field, value) {
				// 清除之前的错误
				if (this.errors[field]) {
					delete this.errors[field]
				}
				// 根据字段进行不同的验证
				switch (field) {
					case 'name':
						if (!value.trim()) {
							this.errors[field] = '请输入姓名'
						} else if (value.length > 20) {
							this.errors[field] = '姓名长度不能超过20个字符'
						}
						break

					case 'gender':
						if (!value) {
							this.errors[field] = '请选择性别'
						}
						break

					case 'birthday':
						if (!value) {
							this.errors[field] = '请选择出生年月'
						}
						break

					case 'mobilePhone':
						if (!value) {
							this.errors[field] = '请输入电话号码'
						} else {
							const mobilePhoneReg = /^1[3-9]\d{9}$/
							if (!mobilePhoneReg.test(value)) {
								this.errors[field] = '请输入有效的手机号码'
							}
						}
						break

					case 'education':
						if (!value) {
							this.errors[field] = '请选择学历'
						}
						break

					case 'graduationDate':
						if (!value) {
							this.errors[field] = '请选择毕业时间'
						} else if (new Date(value) > new Date()) {
							this.errors[field] = '毕业时间不能晚于当前日期'
						}
						break

					case 'oldWork':
						if (!value.trim()) {
							this.errors[field] = '请输入专业'
						} else if (value.length > 50) {
							this.errors[field] = '专业名称长度不能超过50个字符'
						}
						break

					case 'occupation':
						if (!value.trim()) {
							this.errors[field] = '请输入职业'
						} else if (value.length > 30) {
							this.errors[field] = '职业名称长度不能超过30个字符'
						}
						break

					case 'city':
						if (value.length === 0) {
							this.errors[field] = '请选择城市'
						}
						break

					case 'remark':
						if (value.length > 500) {
							this.errors[field] = '备注信息长度不能超过500个字符'
						}
						break
				}
			},
			validateForm() {
				// 对所有字段进行验证
				for (const field in this.formData) {
					this.validateField(field, this.formData[field])
				}

				// 返回是否有错误
				return Object.keys(this.errors).length === 0
			},
			submitForm() {
				const areaName = this.setoutArea ? this.setoutArea.join(',') : ''
				const arriveDate = this.arriveDate + ' ' + this.arriveTime + ':00'
				// 验证表单
				// if (!this.validateForm()) {
					// 表单验证通过，提交数据
					this.formData.signUpUid = ''
					this.formData.token = JSON.parse(uni.getStorageSync('token'))
					this.formData.areaName = areaName
					this.formData.arriveDate = arriveDate
					this.formData.graduateDate = this.graduateYear ? Number(this.graduateYear.substr(0,4)) : 0
					
					// 这里可以添加API请求代码，将数据提交到服务器
					signUpSave(this.formData).then(res => {
						console.log('res',res.data)
						if (res.data.code == 200) {
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							})
							uni.reLaunch({
								url:'/pages/index/success'
							})
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'error'
							})
						}
					})
				// } else {
				// 	// 表单验证失败，显示错误信息
				// 	uni.showToast({
				// 		title: '请检查并修正表单错误',
				// 		icon: 'none'
				// 	})
				// }
			}
		},
		watch: {
			// 监听表单字段变化，实时验证
			'formData.name': function(value) {
				this.validateField('name', value)
			},
			'formData.mobilePhone': function(value) {
				this.validateField('mobilePhone', value)
			},
			'formData.oldWork': function(value) {
				this.validateField('oldWork', value)
			},
			'formData.occupation': function(value) {
				this.validateField('occupation', value)
			},
			'formData.remark': function(value) {
				this.validateField('remark', value)
			}
		}
	}
</script>

<style>
	.container {
		padding: 10px;
		background-color: #f5f5f5;
		height: 80vh;
		overflow-y: auto;
	}

	.form-container {
		background-color: #fff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		margin-bottom: 15px;
	}

	.form-title {
		font-size: 20px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30px;
		color: #333;
	}

	.form-group {
		min-height: 36px;
		margin-bottom: 20px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 5px;
		border-bottom: 1px solid #eaeaea;
	}

	.label {
		font-size: 14px;
		color: #333;
		font-weight: bold;
		width: 30%;
	}

	.input {
		flex: 1;
		height: 40px;
		border: unset;
		padding: 0 5px;
		border-radius: 5px;
		padding: 0 10px;
		font-size: 14px;
		color: #333;
		text-align: right;
	}
	.uni-input{
		font-size: 13px;
		color: #333;
	}

	.w-90 {
		width: 90% !important;
	}

	.radio-group {
		display: flex;
		flex-wrap: wrap;
	}

	.radio-item {
		display: flex;
		align-items: center;
		margin-right: 20px;
	}

	.select-time-btn {
		margin-top: 10px;
		padding: 8px 15px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		cursor: pointer;
	}

	.picker {
		height: 40px;
		border: unset;
		border-radius: 5px;
		padding: 0 5px;
		font-size: 14px;
		color: #666;
		display: flex;
		align-items: center;
	}

	.textarea {
		width: 100%;
		min-height: 100px;
		border: 1px solid #ddd;
		border-radius: 5px;
		padding: 10px;
		font-size: 14px;
		color: #333;
		resize: none;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 30px;
		margin-bottom: 60px;
	}

	.btn {
		width: 48%;
		height: 45px;
		border-radius: 5px;
		font-size: 16px;
		font-weight: 500;
		cursor: pointer;
	}

	.reset-btn {
		background-color: #f5f5f5;
		color: #666;
		border: 1px solid #ddd;
	}

	.submit-btn {
		background-color: #007aff;
		color: #fff;
		border: none;
	}

	.error-message {
		color: #f56c6c;
		font-size: 12px;
		margin-top: 5px;
	}

	/* 错误状态的输入框样式 */
	.input.error,
	.picker.error,
	.textarea.error {
		border-color: #f56c6c;
	}


	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		padding: 30rpx 0;
		color: #333;
	}

	.card-container {
		padding: 20rpx;
	}

	.card-item {
		margin-bottom: 40rpx;
	}

	.card-label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	.upload-area {
		width: 100%;
		height: 400rpx;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #f9f9f9;
		position: relative;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.upload-placeholder {
		text-align: center;
	}

	.upload-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.upload-hint {
		font-size: 24rpx;
		color: #bbb;
	}

	.delete-btn {
		display: block;
		text-align: center;
		color: #ff4500;
		font-size: 26rpx;
		margin-top: 15rpx;
	}

	.tips {
		padding: 20rpx;
		background-color: #f5f5f5;
		border-radius: 12rpx;
		margin-bottom: 40rpx;
	}

	.tips-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.tips text {
		display: block;
		font-size: 24rpx;
		color: #666;
		line-height: 1.8;
	}

	/* .submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #007aff;
  color: white;
  border-radius: 44rpx;
  font-size: 32rpx;
}

.submit-btn[disabled] {
  background-color: #cccccc;
} */

	.content {
		padding: 30rpx;
	}

	.preview-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-top: 40rpx;
		margin-bottom: 20rpx;
	}

	.preview-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.preview-item {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.preview-item image {
		width: 100%;
		height: 100%;
	}

	.default-box {
		padding: 4px 30px;
		border: 1px solid #EFEBE9;
		border-radius: 4px;
		font-size: 12px;
		color: #333;
		display: flex;
		align-items: center;

	}

	.active-default-box {
		background-color: #007aff;
		color: white;
		border: unset !important;
	}
</style>